package com.tiantian.novel.resolver.impl;

import com.tiantian.novel.helper.HttpHelper;
import com.tiantian.novel.helper.PinYinUtil;
import com.tiantian.novel.model.ChapterInfo;
import com.tiantian.novel.model.NovelSummary;
import com.tiantian.novel.resolver.NovelResolver;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.regex.Pattern;

/**
 * 新版笔趣阁类parser
 * https://www.biqiugexx.com/book_21161141/
 *
 * @author wangkai
 * @since 2023/11/12.
 */
public class BiqugeNewNovelResolver implements NovelResolver {
    private static final Logger log = LoggerFactory.getLogger(BiqugeNewNovelResolver.class);
    /**
     * http utils
     */
    private HttpHelper http;

    public BiqugeNewNovelResolver() {
        this.http = new HttpHelper(true);
    }

    @Override
    public NovelSummary resolveNovelSummary(String url) throws Exception {
        log.info("resolve NovelInfo from www 【{}】", url);
        Element body = http.getBody(url);
        // 标题、作者、更新状态、最后更新时间
        Element info = body.selectFirst("div.book").selectFirst("div.info");
        String title = info.selectFirst("h2").text();
        Elements ps = info.selectFirst("div.small").children();
        String author = ps.get(0).text().split("：")[1];
        String updateStatus = ps.get(2).text().split("：")[1];
        String updateTime = ps.get(4).text().split("：")[1];
        String logo = info.selectFirst("div.cover > img").absUrl("src");
        NovelSummary novel = new NovelSummary(PinYinUtil.getShortPinYin(title), url, title, author, updateStatus, updateTime,
                                              logo);
        // 目录
        int begin = body.selectFirst("div.listmain").select("dl>dt").get(1).siblingIndex();
        Elements children = body.selectFirst("div.listmain").selectFirst("dl").children();

        int index = 1;
        for (Element child : children) {
            if (child.siblingIndex() > begin) {
                Element link = child.selectFirst("a");
                novel.add(new ChapterInfo(index++, link.attr("abs:href"), link.text()));
            }
        }
        return novel;
    }

    private Pattern titlePattern = Pattern.compile("第\\w+章\\w+");

    @Override
    public ChapterInfo resovleChapter(String url) throws Exception {
        log.info("resovle ChapterInfo from www 【{}】", url);
        Element body = http.getBody(url);
        if (body == null) {
            log.info("body is null");
            return null;
        }
        Element title = body.selectFirst("div.content>h1");
        if (title == null) {
            log.info("title is null");
            return null;
        }
        // todo 校验是否为[正常]标题,结构为 第一章 土豆新书预览,第1235章 土豆新书预览
        // if(!title.text().matches(titlePattern)){
        //     return
        // }

        Element content = body.getElementById("content");
        if (content == null) {
            log.info("content is null");
            return null;
        }
        String contentText = content.text();
        // 出现了异常
        if (contentText.startsWith("正在手打中，请稍等片刻") && contentText.endsWith(
                "即可获取最新更新")) {
            log.info("contentText:{}", content);
            return null;
        }
        ChapterInfo info = new ChapterInfo(0, url, title.text().trim());
        info.setContent(Jsoup.clean(content.html().replaceAll("&nbsp;", ""), Whitelist.relaxed()));
        return info;
    }

    @Override
    public byte[] getImage(String logo) throws IOException {
        return http.getImage(logo);
    }

}
